package com.me.springcloud.feign;

import static feign.Util.ensureClosed;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONReader;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;

import feign.Response;
import feign.Util;
import feign.codec.Decoder;

/**
 * 自己写的基于fastjson简易Decoder
 * 
 * @author r6yuxx
 *
 */
public class FastJsonDecoder implements Decoder {

	@Override
	public Object decode(Response response, Type type) throws IOException {
		if (response.status() == 404)
			return Util.emptyValueOf(type);
		if (response.body() == null)
			return null;
		Reader reader = response.body().asReader();
		if (!reader.markSupported()) {
			reader = new BufferedReader(reader, 1);
		}
		JSONReader jsonReader = new JSONReader(reader);
		try {
			String str = jsonReader.readString();
			return JSON.parseObject(str, type, JSON.DEFAULT_GENERATE_FEATURE);
		} catch (RuntimeJsonMappingException e) {
			if (e.getCause() != null && e.getCause() instanceof IOException) {
				throw IOException.class.cast(e.getCause());
			}
			throw e;
		} finally {
			ensureClosed(reader);
			ensureClosed(jsonReader);
		}
	}
}
